const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http)
const port = process.env.PORT || 3001;
const Redis = require("./tools/redis");
// import Socket from './tools/Socket';
const Socket =require('./tools/Socket')
const login = require("./src/login");
const api = require("./data/api");


// var port = normalizePort(process.env.PORT || 3002); 
// var https_port = normalizePort(process.env.HTTPS_PORT || 443); //https证书 var opts = { key: fs.readFileSync('pem/openssl/ssl.key'), cert: fs.readFileSync('pem/openssl/ssl.crt') }; var server = http.createServer(handler); var httpsServer = https.createServer(opts, function(req, res) { res.writeHead(200, { "Content-Type": "text/plain" }); res.write("hello https"); res.end(); }); server.listen(port); httpsServer.listen(https_port); server.on('error', onError); server.on('listening', onListening); httpsServer.on('error', onError); httpsServer.on('listening', onListening); //socket.io var io = require('socket.io')({}); <-------- 这里改如何设置 io.attach(server); io.attach(httpsServer);
function result(code=404,msg="非法请求",data={}){
    return {
        code,data,msg
    }
}
 
app.get('/setData',async(req, res)=>{
    let  userinfo={
        username:'zhangsan',
        age:'20'
    };
    let  ress=await Redis.setData("user",userinfo)
    res.json(ress) 
});
app.get('/getData', async function (req, res) {
    let key=12
    let data=await Redis.getData(key)
    res.json(data)
});
app.get('/get', async function (req, res) {
    let data = await Redis.hGet("test1",)
    res.json(data)
});
app.get('/set', async function (req, res) {
    let key = req.query.key
    let val = req.query.val;
    let data = await Redis.hSet("test1",key,val)
    res.json(data)
});
app.get('/del', async function (req, res) {
    let key = req.query.key
    let data = await Redis.hDel("test1",key)
    res.json(data)
});
io.on('connection', async (socket)=> {
    console.log('新加入一个连接。');
    // socket.emit('message', "dengk");
    socket.on('setRoom',async (data)=> {
        console.log(123213);
        
        let res =await login.login(data,socket.id)
        console.log(res);
        if (res.code==400) {
            socket.emit("login", res)
            socket.disconnect()
        }else if(res.code==300){
            io.to(res.data).emit("login", res);
        }else{
            io.emit("getList", {
                code: 200,
                data: {},
                msg: "有用户连接"
            })
        }
    });

    socket.on('chat message', function (data) {
        var toName = data.to;
        var toId = data.id;
        const hashName={}
        // if (toId = hashName[toName]) {
        //   var toSocket = _.findWhere(io.sockets.sockets, { id: toId });
        // //   socket.broadcast.emit("a123", data.msg) 
        //   toSocket.emit('message', data.msg);
        // }
    });
    // 当关闭连接后触发 disconnect 事件
    socket.on('disconnect',async (data)=> {
        // login.delLoginInfo(socket.id)
        io.emit("getList", {
            code:200,
            data:{},
            msg:"有用户断开"
        }) 
    });
});
 

app.get('/wordcloud', async (req, res) => {
    io.emit("wordcloud", {
        type: req.query.type,
        data: req.query.data
    });
    let data= result(200, "发送成功", [])
    res.json(data)
});

app.get('/resolve', async(req, res) => {
    let room = req.query.room
    let type = req.query.type||0;
    let socket_id = await Redis.hGetValue("tokenList", room)
    let data={}
    if (socket_id) {
        if (type==1) {
            data = result(200, "确认登录", req.query.user)
        } else{
            data = result(400, "取消登录", {})
        }
        io.to(socket_id).emit("login", data);
        res.json(data)
    }else{
        res.json(result(404, "非法请求",{
            sid: socket_id, room
        }))
    }
    
   
});

app.get('/', (req, res) => {
    console.log("首页")
    // let data = api
    // res.json(data)
    // res.sendFile();
    // let socket = new SocketName.Socket()
    let socket = new Socket()
    socket.send()
    res.sendFile(__dirname + '/index.html');
});
//同意登录

//拒绝登录
app.get('/reject', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});




app.get("/getlist",(req, res) => {
    let data={}
    // data=io.sockets.clients('/'); 
    data=io.sockets.adapter.rooms
    console.log(io)
    // var clients = io.nsps["/"].sockets;
    res.json(data)
})
app.post('/send', (req, res) => {
    if (req.headers.token=="msg123") {
        let data= {
            code:200,
            data:req.query,
            msg:"返回成功"
        }
        io.emit('chat message',data);
        res.json(data)
    } else {
        res.json({
            code:404,
            data:[],
            msg:"token错误"
        })
    
    }
   
});





http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
});
